// import { httpError } from "@midwayjs/core";
import { Inject, Middleware } from "@midwayjs/decorator";
import { JwtService } from "@midwayjs/jwt";
import { Context, NextFunction } from "@midwayjs/koa";
import { ErrMsg } from "../common/ErrCode";
import { Tools } from "../common/Tools";
import { IReturnData } from "../interfaces/IBase.interface";

@Middleware()
export class JwtMiddleware{

    @Inject()
    jwtService:JwtService;

    public async makeSign(payload:any):Promise<any>{
        payload = Tools.clone(payload);
        if(payload != null){
            if(typeof(payload) == 'string' || typeof(payload) == 'number'){
                payload = {
                    data:payload
                }
            }
            let to = await this.jwtService.sign(payload);
            return to;
        }
        return payload;
    }
      // 配置忽略鉴权的路由地址
    // public match(ctx: Context): boolean {
    //     const ignore = ctx.path.indexOf('/api/login') !== -1;
    //     return !ignore;
    // }

 
    resolve(){
        return async (ctx:Context,next:NextFunction) => {
            // if (!ctx.headers['authorization']) {
            //     throw new httpError.UnauthorizedError();
            // }
            // const parts = ctx.get('authorization').trim().split(' ');
            // if (parts.length !== 2) {
            //     throw new httpError.UnauthorizedError();
            // }
            // const [scheme, token] = parts;
            // if (/^Bearer$/i.test(scheme)) {
            //     try {
            //         //jwt.verify方法验证token是否有效
            //         await this.jwtService.verify(token, {
            //         complete: true,
            //         });
            //     } catch (error) {
            //         //token过期 生成新的token
            //     //   const newToken = //getToken(user);
            //         //将新token放入Authorization中返回给前端
            //     //   ctx.set('Authorization', newToken);
            //     }
            //     console.log(ctx);
            //     await next();
            // }
            const result:IReturnData<any> =  await next();
            if(result.data != null && result.data != ""){
                // result.data = await this.makeSign(result.data);
                result.data = Tools.formatData(result.data);
            }

            // let check = await this.jwtService.decode(result.data);
            // console.log(check);

            if(result.message == null){
                result.message = ErrMsg[result.code];
            }
            return result;
        }
    }


}